package com.lkd.handler;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.StatusInfo;
import com.lkd.contract.VmStatusContract;
import com.lkd.emq.Topic;
import com.lkd.entity.TaskEntity;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

/**
 * 创建工单，运维
 */
@Component
@Topic(TopicConfig.VMS_STATUS_TOPIC)
@Slf4j
public class VMStatusHandler implements MsgHandler {

    @Autowired
    private VMService vmService;

    @Autowired
    private TaskService taskService;

    @Override
    public void process(String jsonMsg) throws IOException {
        VmStatusContract vmStatusContract = JsonUtil.getByJson(jsonMsg, VmStatusContract.class);
        if (vmStatusContract == null || vmStatusContract.getStatusInfo().size() == 0) {
            return;
        }
        //售货机所有零件的状态
        List<StatusInfo> statusInfo = vmStatusContract.getStatusInfo();
        //判断零件状态
        for (StatusInfo info : statusInfo) {
            if (!info.isStatus()) {

                try {
                    //查询售货机
                    VmVO vmInfo = vmService.getVMInfo(vmStatusContract.getInnerCode());
                    if (vmInfo == null) {
                        return;
                    }

                    int leastUser = taskService.getLeastUser(vmInfo.getRegionId(), true);

                    if (leastUser != 0) {
                        TaskViewModel task = new TaskViewModel();
                        task.setCreateType(0);
                        task.setInnerCode(vmInfo.getInnerCode());
                        task.setUserId(leastUser);
                        task.setAssignorId(0);
                        task.setProductType(VMSystem.TASK_TYPE_REPAIR);
                        task.setDesc(jsonMsg);

                        taskService.createTask(task);

                        LambdaUpdateWrapper<TaskEntity> luw=new LambdaUpdateWrapper();
                    }
                } catch (Exception e) {
                    log.error("创建自动维修工单失败，msg is:"+jsonMsg);
                }
            }
        }

    }
}

